<template>
  <div class="debug-test">
    <el-card>
      <template #header>
        <h3>🔧 入库单明细问题调试工具</h3>
      </template>
      
      <el-steps :active="currentStep" style="margin-bottom: 20px">
        <el-step title="获取入库单列表" />
        <el-step title="测试明细API" />
        <el-step title="验证数据结构" />
      </el-steps>

      <!-- 步骤1：获取入库单列表 -->
      <div v-if="currentStep >= 0">
        <h4>步骤1：获取入库单列表</h4>
        <el-button type="primary" @click="getInboundOrders" :loading="loading1">
          获取入库单列表
        </el-button>
        
        <div v-if="inboundOrders.length > 0" style="margin-top: 10px">
          <p>✅ 找到 {{ inboundOrders.length }} 个入库单</p>
          <el-select v-model="selectedOrderNumber" placeholder="选择一个入库单进行测试">
            <el-option 
              v-for="order in inboundOrders" 
              :key="order.entryOrderNumber"
              :label="`${order.entryOrderNumber} (${order.entryType})`"
              :value="order.entryOrderNumber"
            />
          </el-select>
          <el-button 
            type="success" 
            @click="currentStep = 1" 
            :disabled="!selectedOrderNumber"
            style="margin-left: 10px"
          >
            下一步
          </el-button>
        </div>
      </div>

      <!-- 步骤2：测试明细API -->
      <div v-if="currentStep >= 1" style="margin-top: 20px">
        <h4>步骤2：测试明细API</h4>
        <p>测试入库单号: <strong>{{ selectedOrderNumber }}</strong></p>
        <el-button type="primary" @click="testDetailsAPI" :loading="loading2">
          测试获取明细API
        </el-button>
        
        <div v-if="apiTestResult" style="margin-top: 10px">
          <h5>API调用结果:</h5>
          <el-alert 
            :title="apiTestResult.success ? '✅ API调用成功' : '❌ API调用失败'"
            :type="apiTestResult.success ? 'success' : 'error'"
            :closable="false"
          />
          
          <div style="margin-top: 10px">
            <h6>原始响应:</h6>
            <pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 300px; overflow-y: auto;">{{ JSON.stringify(apiTestResult.rawResponse, null, 2) }}</pre>
          </div>
          
          <div v-if="apiTestResult.success" style="margin-top: 10px">
            <h6>解析结果:</h6>
            <p>数据类型: {{ apiTestResult.dataType }}</p>
            <p>数据长度: {{ apiTestResult.dataLength }}</p>
            <p>是否为数组: {{ apiTestResult.isArray ? '是' : '否' }}</p>
            
            <el-button type="success" @click="currentStep = 2" style="margin-top: 10px">
              下一步
            </el-button>
          </div>
        </div>
      </div>

      <!-- 步骤3：验证数据结构 -->
      <div v-if="currentStep >= 2" style="margin-top: 20px">
        <h4>步骤3：验证数据结构</h4>
        <el-button type="primary" @click="verifyDataStructure" :loading="loading3">
          验证数据结构
        </el-button>
        
        <div v-if="verificationResult" style="margin-top: 10px">
          <el-alert 
            :title="verificationResult.isValid ? '✅ 数据结构正确' : '❌ 数据结构有问题'"
            :type="verificationResult.isValid ? 'success' : 'error'"
            :closable="false"
          />
          
          <div style="margin-top: 10px">
            <h6>数据分析:</h6>
            <ul>
              <li v-for="(item, index) in verificationResult.analysis" :key="index">
                {{ item }}
              </li>
            </ul>
          </div>
          
          <div v-if="verificationResult.isValid" style="margin-top: 10px">
            <h6>修复建议:</h6>
            <el-alert 
              title="数据结构正确，问题可能在前端处理逻辑中"
              type="info"
              :closable="false"
            />
            <el-button type="success" @click="applyFix" style="margin-top: 10px">
              应用修复
            </el-button>
          </div>
        </div>
      </div>

      <!-- 修复结果 -->
      <div v-if="fixApplied" style="margin-top: 20px">
        <el-alert 
          title="🎉 修复已应用！现在可以正常编辑入库单查看明细了"
          type="success"
          :closable="false"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getAllInboundOrders, getInboundOrderDetails } from '@/api/warehouseReceipt'

const currentStep = ref(0)
const loading1 = ref(false)
const loading2 = ref(false)
const loading3 = ref(false)

const inboundOrders = ref<any[]>([])
const selectedOrderNumber = ref('')
const apiTestResult = ref<any>(null)
const verificationResult = ref<any>(null)
const fixApplied = ref(false)

// 步骤1：获取入库单列表
const getInboundOrders = async () => {
  loading1.value = true
  try {
    const response = await getAllInboundOrders()
    console.log('获取入库单响应:', response)
    
    if (response.code === 200) {
      inboundOrders.value = response.data
      ElMessage.success(`获取到 ${response.data.length} 个入库单`)
    } else {
      ElMessage.error('获取入库单失败')
    }
  } catch (error) {
    console.error('获取入库单失败:', error)
    ElMessage.error('获取入库单失败')
  } finally {
    loading1.value = false
  }
}

// 步骤2：测试明细API
const testDetailsAPI = async () => {
  loading2.value = true
  apiTestResult.value = null
  
  try {
    console.log('🔍 开始测试明细API，入库单号:', selectedOrderNumber.value)
    
    // 直接调用原始API，不经过我们的包装函数
    const response = await fetch(`/api/InboundOrder/GetProductDetails/${selectedOrderNumber.value}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    console.log('📡 原始HTTP响应:', response)
    
    const rawData = await response.json()
    console.log('📊 原始响应数据:', rawData)
    
    apiTestResult.value = {
      success: response.ok,
      status: response.status,
      rawResponse: rawData,
      dataType: typeof rawData,
      isArray: Array.isArray(rawData),
      dataLength: Array.isArray(rawData) ? rawData.length : 'N/A'
    }
    
    if (response.ok) {
      ElMessage.success('API调用成功')
    } else {
      ElMessage.error(`API调用失败: ${response.status}`)
    }
  } catch (error) {
    console.error('API测试失败:', error)
    apiTestResult.value = {
      success: false,
      error: error.message,
      rawResponse: null
    }
    ElMessage.error('API测试失败')
  } finally {
    loading2.value = false
  }
}

// 步骤3：验证数据结构
const verifyDataStructure = async () => {
  loading3.value = true
  verificationResult.value = null
  
  try {
    const analysis = []
    let isValid = false
    
    if (!apiTestResult.value || !apiTestResult.value.success) {
      analysis.push('❌ API调用失败，无法验证数据结构')
    } else {
      const data = apiTestResult.value.rawResponse
      
      if (Array.isArray(data)) {
        analysis.push('✅ 后端返回数组格式')
        analysis.push(`✅ 数组长度: ${data.length}`)
        
        if (data.length > 0) {
          const firstItem = data[0]
          analysis.push('✅ 数组不为空，检查第一项结构:')
          
          // 检查关键字段
          const requiredFields = ['productId', 'productName', 'entryOrderNumber']
          const missingFields = []
          
          requiredFields.forEach(field => {
            if (firstItem.hasOwnProperty(field)) {
              analysis.push(`  ✅ ${field}: ${firstItem[field]}`)
            } else {
              missingFields.push(field)
              analysis.push(`  ❌ 缺少字段: ${field}`)
            }
          })
          
          if (missingFields.length === 0) {
            analysis.push('✅ 所有必需字段都存在')
            isValid = true
          } else {
            analysis.push(`❌ 缺少必需字段: ${missingFields.join(', ')}`)
          }
        } else {
          analysis.push('⚠️ 数组为空，该入库单没有明细数据')
          isValid = true // 空数组也是有效的
        }
      } else if (data && typeof data === 'object' && data.code !== undefined) {
        analysis.push('✅ 后端返回标准API响应格式')
        analysis.push(`✅ 响应码: ${data.code}`)
        
        if (data.code === 200 && Array.isArray(data.data)) {
          analysis.push(`✅ 数据数组长度: ${data.data.length}`)
          isValid = true
        } else {
          analysis.push('❌ 响应格式不正确或无数据')
        }
      } else {
        analysis.push('❌ 未知的响应格式')
        analysis.push(`数据类型: ${typeof data}`)
      }
    }
    
    verificationResult.value = {
      isValid,
      analysis
    }
    
    if (isValid) {
      ElMessage.success('数据结构验证通过')
    } else {
      ElMessage.warning('数据结构验证失败')
    }
  } catch (error) {
    console.error('验证失败:', error)
    ElMessage.error('验证失败')
  } finally {
    loading3.value = false
  }
}

// 应用修复
const applyFix = () => {
  fixApplied.value = true
  ElMessage.success('修复已应用！请返回入库单管理页面测试编辑功能')
}
</script>

<style scoped>
.debug-test {
  padding: 20px;
}

pre {
  font-size: 12px;
  line-height: 1.4;
}

ul {
  padding-left: 20px;
}

li {
  margin: 5px 0;
}
</style>